/**
 * 
 */
package org.gov.vis.master.gui.listener;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import org.gov.vis.common.exceptions.InvalidInputException;
import org.gov.vis.gui.util.ErrorsDisplayJPanel;
import org.gov.vis.main.Main;
import org.gov.vis.master.controller.OtherCtlr;
import org.gov.vis.master.controller.OtherCtlrImpl;
import org.gov.vis.master.dto.OtherDto;
import org.gov.vis.master.gui.EditOthersDialog;
import org.gov.vis.master.gui.ViewOthersDialog;
import org.gov.vis.util.GuiConstants;
import org.gov.vis.util.Util;


/**
 * @author Srikanth
 *
 */
public class EditOthersListener implements ActionListener, BaseListener{

	final private ResourceBundle rb = Util.getResources();

	private OtherCtlr otherCtlr = new OtherCtlrImpl();

	private EditOthersDialog editOthersDialog;

	private ErrorsDisplayJPanel errorMsgPanel;
	private OtherDto otherDto;
	public EditOthersListener(EditOthersDialog editOthersDialog) {
		// TODO Auto-generated constructor stub
		this.editOthersDialog = editOthersDialog;
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setGuiDetailsToDto(Object _guiObject) {
		EditOthersDialog _editOthersDialog =(EditOthersDialog)_guiObject;
		otherDto = new OtherDto();
		otherDto.setCode(_editOthersDialog.getTxtFldCode().getText());
		otherDto.setNameOfOrg(_editOthersDialog.getTxtFldOrg().getText());
		otherDto.setNameOfAIWorker(_editOthersDialog.getTxtFldAIWorker().getText());
		otherDto.setHeadQuarter(_editOthersDialog.getTxtFldHeadQuarter().getText());
		otherDto.setJuridiction(_editOthersDialog.getTxtFldJurisdiction().getText());
		otherDto.setMandal(_editOthersDialog.getTxtFldMandal().getText());
		otherDto.setDistrict(_editOthersDialog.getTxtFldDistrict().getText());
		otherDto.setOtherId((Long)_editOthersDialog.getHidnObject());


	}

	@Override
	public void setDtoDetailsToGui(Object _dtoObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void clearGUILabelColors(Color _labelColor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent actionEvent) {
	
		errorMsgPanel = new ErrorsDisplayJPanel(editOthersDialog.getjPanel1());
		errorMsgPanel.clearMsgPanel();


		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_update"))){

			//Method called to either Add or Edit the Other details
			addOrEditOther();
		}

		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_delete"))){
			
			int response = JOptionPane.showConfirmDialog(null, GuiConstants.DELETE_CONFIRM_MSG, "Confirm",
			        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			    
		    if (response == JOptionPane.YES_OPTION) {
		      // User clicked YES.
		    	deleteOthers(actionEvent);
		    	//Thread.sleep(GuiConstants.THREAD_SLEEP_TIME);
				
				String searchText = editOthersDialog.getSearchText();
				
				// It is basically doing back button functionality. Please, understand the logic and write the comments.
				//Replace double quotes with appropriate Dialog title.
				ViewOthersDialog viewOthersDialog = new ViewOthersDialog(Main.getMainFrame(), "View Others", false);
				for(ActionListener actionListener: viewOthersDialog.getSearchBtn().getActionListeners()) { 
				  ViewOthersListener viewOtherList = (ViewOthersListener)actionListener;
				  viewOthersDialog.getCodeTxtBx().setText(searchText);
				  
				  viewOtherList.actionPerformed(new ActionEvent(viewOthersDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
				}
		    } else if (response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION) {
		      return;
		    }

		}
	}

	private void addOrEditOther() {

		//Method called to set the Field's Labels to default Black color
		clearGUILabelColors(blackColor);

		//Method to set the Screen's data to  the DTO Object
		setGuiDetailsToDto(editOthersDialog);

		try{
			//Method called to Add or Edit the Other
			otherCtlr.addOrEditOther(otherDto);
			
			JOptionPane.showMessageDialog(editOthersDialog, rb.getString(GuiConstants.MASTER_EDIT_OTHER_SUCCESS));
			
			//closing Dialog Box, Edit Others.
			editOthersDialog.dispose();
			
			
			Thread.sleep(GuiConstants.THREAD_SLEEP_TIME);
			
			String searchText = editOthersDialog.getSearchText();
			
			// It is basically doing back button functionality. Please, understand the logic and write the comments.
			//Replace double quotes with appropriate Dialog title.
			ViewOthersDialog viewOthersDialog = new ViewOthersDialog(Main.getMainFrame(), "View Others", false);
			for(ActionListener actionListener: viewOthersDialog.getSearchBtn().getActionListeners()) { 
			  ViewOthersListener viewOtherList = (ViewOthersListener)actionListener;
			  viewOthersDialog.getCodeTxtBx().setText(searchText);
			  
			  viewOtherList.actionPerformed(new ActionEvent(viewOthersDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
			} 
			
			
		}catch(Exception e){
			//e.printStackTrace();
			List<String> errorMsgLst = new ArrayList<String>();
			if(e instanceof InvalidInputException){
				final HashMap<String,String> _exceptions = OtherCtlrImpl.errorMsgs;
				if (_exceptions != null && !_exceptions.isEmpty()) {
					String errMsg = null;
					if(_exceptions.containsKey(rb.getString("dialog_label_othr_code").toUpperCase())){
						editOthersDialog.getLblCode().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_othr_code").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_othr_nmeoforg").toUpperCase())){
						editOthersDialog.getLblOrganizationName().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_othr_nmeoforg").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					errorMsgPanel.setErrorMessages(errorMsgLst);					
				} else {
					//log.debug(e.getMessage(), e);
				}
			}
			else{
				errorMsgLst.add(e.getMessage());
				errorMsgPanel.setErrorMessages(errorMsgLst);
			}
		}		


	}

	private void deleteOthers(ActionEvent actionEvent) {

		Long othersId = (Long)editOthersDialog.getHidnObject();
		try {
			otherCtlr.deleteOther(othersId);
			
			JOptionPane.showMessageDialog(editOthersDialog, rb.getString(GuiConstants.MASTER_DELETE_OTHER_SUCCESS));
			
			editOthersDialog.dispose();
			
		} catch (Exception e) {
			List<String> errorMsgLst = new ArrayList<String>();
			errorMsgLst.add(e.getMessage());
			errorMsgPanel.setErrorMessages(errorMsgLst);

		}
	}

}
